import axios from 'axios'
// import { useSelector } from "react-redux";
import { createBrowserHistory } from 'history';

let history = createBrowserHistory()

let service = axios.create({
    timeout: 10 * 1000,
    baseURL: process.env.REACT_APP_BASE_API
})

service.interceptors.request.use(
    (config) => {
        // let token=useSelector((newstate:any)=>newstate.token)

        config.headers['token'] = localStorage.getItem('token')
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

service.interceptors.response.use(
    (res) => {
        if (res.data.code=='10119') {
            localStorage.removeItem('token')
            history.push('/login')
            history.go(0)
        }
        return res
    },
    (error) => {
        if (error.response.status == 401) {
            alert('登陆过期，请重新登录')
            localStorage.removeItem('token')
            history.push('/login')
        } else if (error.response.status == 404) {
            alert('访问路径有误')
        } else if (error.response.status == 500) {
            alert('服务器内部错误')
        } else if (error.response.status == 503) {
            alert('服务器无法提供服务')
        }
        return Promise.reject(error)
    }
)

export default service